import asyncio

import nest_asyncio
from aiogram import Dispatcher, Bot, types
from aiogram.client.session.aiohttp import AiohttpSession
from aiogram.client.telegram import TelegramAPIServer
from loguru import logger

from tg_bot.config import load_config, setup_django

setup_django()

from tg_bot import middlewares
from tg_bot import handlers
from tg_bot.middlewares.config_setter import ConfigSetter
from tg_bot.services import broadcaster
from database.models import Config, TgUser

nest_asyncio.apply()


async def on_startup(bot: Bot, admin_ids: list[int]):
    commands = [
        types.BotCommand(command='start', description='Запустить бота'),
        types.BotCommand(command='menu', description='Меню'),
    ]
    admin_commands = [
        types.BotCommand(command='admin', description='Админ меню'),
        types.BotCommand(command='open_shift', description='Открыть смену'),
        types.BotCommand(command='close_shift', description='Закрыть смену'),
    ]
    await bot.set_my_commands(
        commands,
        scope=types.BotCommandScopeDefault()
    )
    for user in TgUser.get_admins():
        try:
            await bot.set_my_commands(
                commands+admin_commands,
                scope=types.BotCommandScopeChat(
                    chat_id=user.user_id
                )
            )
        except Exception as e:
            logger.debug(f'{e} = {user}')
    await broadcaster.broadcast(bot, admin_ids, "Бот успешно запущен!")


async def main():
    session = AiohttpSession(
        api=TelegramAPIServer.from_base('http://127.0.0.1:8081/')
    )

    logger.add('logs/{time:DD-MM-YYYY}.log', level='INFO', encoding='utf-8', rotation="12:00", retention='7 days')
    config = load_config(".env")

    main_dp = Dispatcher()

    logger.info('Регистрирую Middlewares.')
    main_dp.update.outer_middleware(ConfigSetter(config=config))
    middlewares.setup(main_dp)

    logger.info('Регистрирую Handlers.')
    handlers.setup(main_dp)

    logger.info('Запускаю бота.')

    bot = Bot(token=config.tg_bot.token, session=session)
    bot.default.parse_mode = 'HTML'
    bot_info = await bot.get_me()
    bot_config = Config.objects.filter(bot_id=bot_info.id,
                                       bot_url=bot_info.username).first()

    if not bot_config:
        Config.objects.create(
            bot_id=bot_info.id,
            bot_url=bot_info.username
        )
    # start
    try:
        config.misc.scheduler.start()
        await bot.delete_webhook(drop_pending_updates=True)
        await on_startup(bot, config.tg_bot.admin_ids)
        await main_dp.start_polling(bot)
    finally:
        await bot.session.close()


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except (KeyboardInterrupt, SystemExit):
        logger.info("Останавливаю бота!")
